package com.tomato.lock.common;

import lombok.AllArgsConstructor;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static java.text.MessageFormat.format;

@AllArgsConstructor
public class LockDeadTest implements Runnable {
    static final Lock lock1 = new ReentrantLock();
    static final Lock lock2 = new ReentrantLock();
    boolean flag;

    public static void main(String[] args) {
        Thread t1 = new Thread(new LockDeadTest(true), "tomato-thread-1");
        Thread t2 = new Thread(new LockDeadTest(false), "tomato-thread-2");
        t1.start();
        t2.start();
    }

    @Override
    public void run() {
        try {
            // flag 为 true,则先获取锁1然后在锁1里面获取锁2
            if (flag) {
                try {
                    lock1.lock();
                    System.out.println(format("{0}:获取到了lock1锁,开始执行任务", Thread.currentThread().getName()));
                    // 模拟耗时操作，这里休眠1s
                    Thread.sleep(1000);
                    lock2.lock();
                    System.out.println(format("{0}:获取到lock2锁{1}", Thread.currentThread().getName(), "成功,开始执行任务"));
                } finally {
                    lock1.unlock();
                    lock2.unlock();
                }
            } else {
              try {
                  lock2.lock();
                  System.out.println(format("{0}:获取到了lock2锁,开始执行任务", Thread.currentThread().getName()));
                  Thread.sleep(1000);
                  lock1.lock();
                  System.out.println(format("{0}:获取到lock1锁{1}", Thread.currentThread().getName(), "成功,开始执行任务"));
              } finally {
                  lock2.unlock();
                  lock1.unlock();
              }
            }
        } catch (InterruptedException e) {
            System.out.println("发生了中断: " + e.getMessage());
        }


    }
}
